﻿$(function () {
    $("#submit").click(function () {
        Submit();
    });

    $("#body").keypress(function (event) {
        if (event.which == '13') {
            Submit();
        }
    });

    $("#Title").keyup(function (event) {
        UpdateUrl(false);
    });

    $("#Title").change(function (event) {
        UpdateUrl(false);
    });

    $("#Url").change(function (event) {
        UpdateUrl(true);
    });

});

function Submit() {

    $("#submit").hide();

    var input = {
        ID: $("#id").val(),
        Title: $("#Title").val(),
        Url: $("#Url").val(),
        Content: $("#Content").val()
    };

    Ajax({
        url: "/Pages/Save",
        data: JSON.stringify(input),
        success: function (data) {
            if (data.IsValid == false) {
                ShowValidationErrors(data);
            } else if (data.IsSaved == true) {
                location.href = "/Pages?msg=1";
            }
        },
        complete: function () {
            $("#submit").show();
        }
    });
}

function UpdateUrl(isSelf) {
    var url = "";
    if (isSelf) {
        url = $("#Url").val();
        url = jQuery.trim(url);
        url = url.replace(/ /gi, "-");
    } else {
        var title = $("#Title").val();
        title = jQuery.trim(title);
        url = title.replace(/ /gi, "-");
    }
    $("#Url").val(url);
}